package com.dashihui.distribution.ui.activity;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.dashihui.distribution.R;
import com.dashihui.distribution.business.entity.EtySendToUI;
import com.dashihui.distribution.common.base.BaseActivity;
import com.dashihui.distribution.common.base.Contracts;
import com.dashihui.distribution.ui.dialog.DialogVersion;
import com.dashihui.distribution.utils.bean.JsonBean;
import com.dashihui.distribution.utils.preferences.UtilPreferences;

import com.gprinter.command.EscCommand;
import com.gprinter.command.GpCom;
import com.gprinter.io.GpDevice;
import com.gprinter.service.GpPrintService;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.apache.commons.lang.ArrayUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Vector;

public class AtyWelcome extends BaseActivity {
    private int mPrinterIndex = 0;
    private ArrayList<JsonBean> jsonList = new ArrayList<>();
    public static final String CONNECT_STATUS = "connect.status";
    private ProgressBar mPb;
    private String POSITION_LEFT = "1";
    private String POSITION_CENTER = "2";
    private String SIZE_BIG = "1";
    private BluetoothAdapter bluetoothAdapter;
    private String data;
    private WebView mWvPre;
    private String isUpdate = "";
    public static final String DEBUG_TAG = "AtyWelcome";
    public static final int REQUEST_ENABLE_BT = 2;
    public static final int REQUEST_CONNECT_DEVICE = 3;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    mFlProgress.setVisibility(View.VISIBLE);
                    mWvPre.setClickable(false);
                    break;
                case 1:
                    mFlProgress.setVisibility(View.GONE);
                    mWvPre.setClickable(true);
                    break;
                case 2:
                    if (!(checkPrint() && checkContectPrint())) {
                        checkBlutooth();
                    }
                    break;
            }
        }
    };
    private FrameLayout mFlProgress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.aty_welcome);
        connection();
        initView();
        //开启服务
        initData();
        //检查版本
        checkVersion();

    }


    private void initView() {
        mWvPre = (WebView) findViewById(R.id.wvPre);
        mPb = (ProgressBar) findViewById(R.id.pb);
        mFlProgress = (FrameLayout) findViewById(R.id.flProgress);
    }

    @Override
    public void onSuccess(EtySendToUI successEty) {
    }

    @Override
    public void onFailure(EtySendToUI failureEty) {
    }

    //监听返回键
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWvPre.canGoBack()) {
            mWvPre.goBack();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }
    private String getVersionName(){
        PackageManager manager = this.getPackageManager();
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(this.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return info.versionName;
    }
    /**
     * 检测是否需要升级
     */
    private void checkVersion() {
        RequestParams params = new RequestParams();
        //A为Android版本
        params.addBodyParameter("TYPE", "A");
        params.addBodyParameter("VERSION",getVersionName());
        Log.i(DEBUG_TAG,getVersionName());
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Contracts.ADDRESS + Contracts.CHECKVERSION,
                params,
                new RequestCallBack<String>() {

                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        try {
                            JSONObject jsonObject1 = new JSONObject(responseInfo.result);
                            JSONObject object = jsonObject1.getJSONObject("object");
                            isUpdate = object.getString("updateflg");
                            if (isUpdate.equals(Contracts.NEW_UPDATE)) {
                                Intent intent = new Intent(AtyWelcome.this, DialogVersion.class);
                                intent.putExtra("downurl", object.getString("downurl"));
                                intent.putExtra("curver", object.getString("curver"));
                                intent.putExtra("fileName", object.getString("fileName"));
                                startActivity(intent);

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                    }
                });
    }

    /**
     * 初始化数据,并添加JavascriptInterface
     */
    @SuppressLint("JavascriptInterface")
    private void initData() {
        WebSettings settings = mWvPre.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDefaultTextEncodingName("utf-8");
        mWvPre.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mWvPre.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWvPre.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    handler.sendEmptyMessage(1);
                } else {
                    handler.sendEmptyMessage(0);
                }
                super.onProgressChanged(view, newProgress);
            }
        });
        mWvPre.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                mWvPre.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                try {
                    //连接打印机
                    mGpService.openPort(Contracts.PRINTERID, Contracts.PORTTYPE, UtilPreferences.getString(AtyWelcome.this, Contracts.BLUETOOTH_ADDRESS, null), Contracts.PORTNUMBER);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                super.onPageFinished(view, url);
            }
        });
        mWvPre.loadUrl(Contracts.ADDRESS);

        mWvPre.addJavascriptInterface(new DJavascriptInterface(), "android");
    }

    /**
     * Javascript用来调用webView的接口
     */
    public class DJavascriptInterface {
        @android.webkit.JavascriptInterface
        public void print(String json) {
            handler.sendEmptyMessage(0);
            data = json;
            //自动连接打印机
//            Contracts.connectPrinter(this,mGpService0);
            Log.i("json", data);

            if (!(checkContectPrint() && checkPrint())) {
                checkBlutooth();
            }
            //打印
            printReceiptClicked();
        }
    }

    /**
     * 检测蓝牙状态
     */
    private void checkBlutooth() {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "此设备不支持蓝牙", Toast.LENGTH_SHORT).show();
            return;
        }
        handler.sendEmptyMessage(1);
        if (bluetoothAdapter.isEnabled()) {
            //检测打印机及连接状态
            if (!(checkPrint() && checkContectPrint())) {
                handler.sendEmptyMessage(0);
                Intent intent = new Intent(AtyWelcome.this,
                        AtyBluetoothDeviceList.class);
                boolean[] state = getConnectState();
                intent.putExtra(CONNECT_STATUS, state);
                startActivityForResult(intent,
                        REQUEST_CONNECT_DEVICE);
            }
            handler.sendEmptyMessage(0);


        } else {
            //打开蓝牙
            Intent enableIntent = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent,
                    REQUEST_ENABLE_BT);
            handler.sendEmptyMessage(1);
        }
//        }
    }

    /**
     * 获取连接状态
     *
     * @return 确定状态
     */
    public boolean[] getConnectState() {
        boolean[] state = new boolean[GpPrintService.MAX_PRINTER_CNT];
        for (int i = 0; i < GpPrintService.MAX_PRINTER_CNT; i++) {
            state[i] = false;
        }
        for (int i = 0; i < GpPrintService.MAX_PRINTER_CNT; i++) {
            try {
                if (mGpService.getPrinterConnectStatus(i) == GpDevice.STATE_CONNECTED) {
                    state[i] = true;
                }
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return state;
    }


    /**
     * 解析json
     */
    private ArrayList<JsonBean> getJsonData() {
        try {
            Log.i("DATA", data);
            JSONArray jsonArray = new JSONArray(data);
            for (int i = 0; i < jsonArray.length(); i++) {
                JsonBean bean = new JsonBean();
                JSONObject jso = jsonArray.optJSONObject(i);
                bean.position = jso.getString("position");
                bean.size = jso.getString("size");
                bean.rowContent = jso.getString("rowContent");
                jsonList.add(bean);
            }
            return jsonList;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //检测蓝牙和打印机
        checkBlutooth();
        return null;
    }

    /**
     * 检测打印机连接状态
     *
     * @return true:已连接,false:打印机断开
     */
    private boolean checkContectPrint() {
        try {
            int status = mGpService.getPrinterConnectStatus(0);
            String str = new String();
            if (status == GpDevice.STATE_CONNECTED) {
                str = "打印机已连接";
                Toast.makeText(getApplicationContext(),
                        "打印机连接状态：" + str, Toast.LENGTH_SHORT).show();
                return true;
            } else {
                str = "打印机断开";
                Log.i(DEBUG_TAG, "打印机连接状态：" + str);
                return false;
            }
        } catch (RemoteException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return false;
    }

    /**
     * 检查打印机状态
     *
     * @return true:打印机正常
     */
    private boolean checkPrint() {
        try {
            int status = mGpService.queryPrinterStatus(mPrinterIndex, 500);
            String str = new String();
            if (status == GpCom.STATE_NO_ERR) {
                str = "打印机正常";
                return true;
            } else {
                str = "打印机 ";
                if ((byte) (status & GpCom.STATE_OFFLINE) > 0) {
                    str += "脱机";
                }
                if ((byte) (status & GpCom.STATE_PAPER_ERR) > 0) {
                    str += "缺纸";
                }
                if ((byte) (status & GpCom.STATE_COVER_OPEN) > 0) {
                    str += "打印机开盖";
                }
                if ((byte) (status & GpCom.STATE_ERR_OCCURS) > 0) {
                    str += "打印机出错";
                }
                if ((byte) (status & GpCom.STATE_TIMES_OUT) > 0) {
                    str += "查询超时";
                }
                Toast.makeText(getApplicationContext(),
                        "打印机状态：" + str, Toast.LENGTH_SHORT).show();

                return false;
            }
        } catch (RemoteException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return true;
    }

    /**
     * 发送打印命令,可发送图片,文字,二维码命令,还可设置文字大小及对齐方式
     */
    void sendReceipt() {
        EscCommand esc = new EscCommand();
        esc.addPrintAndFeedLines((byte) 3);
        ArrayList<JsonBean> list = getJsonData();
        for (int i = 0; i < list.size(); i++) {
            JsonBean bean = list.get(i);
            esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, sizeText(bean.size), sizeText(bean.size), EscCommand.ENABLE.OFF);
            esc.addSelectJustification(positionText(bean.position));
            esc.addText(bean.rowContent + "\n");
        }
       /* *//*打印图片*//*
        Bitmap b = BitmapFactory.decodeStream(getResources(),
                R.drawable.gprinter);
        esc.addRastBitImage(b,b.getWidth(),0);   //打印图片


		/*QRCode命令打印
            此命令只在支持QRCode命令打印的机型才能使用。
			在不支持二维码指令打印的机型上，则需要发送二维条码图片
		*/
        /*esc.addText("Print QRcode\n");   //  打印文字
        esc.addSelectErrorCorrectionLevelForQRCode((byte)0x31); //设置纠错等级
		esc.addSelectSizeOfModuleForQRCode((byte)3);//设置qrcode模块大小
		esc.addStoreQRCodeData("www.gprinter.com.cn");//设置qrcode内容
		esc.addPrintQRCode();//打印QRCode
		esc.addPrintAndLineFeed();

		*/

        Vector<Byte> datas = esc.getCommand(); //发送数据
        Byte[] Bytes = datas.toArray(new Byte[datas.size()]);
        byte[] bytes = ArrayUtils.toPrimitive(Bytes);
        String str = Base64.encodeToString(bytes, Base64.DEFAULT);
        int rel;
        try {
            rel = mGpService.sendEscCommand(mPrinterIndex, str);
            GpCom.ERROR_CODE r = GpCom.ERROR_CODE.values()[rel];
            if (r != GpCom.ERROR_CODE.SUCCESS) {
                Toast.makeText(getApplicationContext(), GpCom.getErrorText(r),
                        Toast.LENGTH_SHORT).show();
            }
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        handler.sendEmptyMessageDelayed(1, 500);

    }

    /**
     * 判断文字大小
     *
     * @param size
     * @return ON为大字体, OFF为小字体
     */
    private EscCommand.ENABLE sizeText(String size) {
        if (size.equals(SIZE_BIG)) {
            return EscCommand.ENABLE.ON;
        } else {
            return EscCommand.ENABLE.OFF;
        }
    }

    /**
     * 判断打印居中，居左，居右
     *
     * @param position
     * @return Esc命令,
     */
    private EscCommand.JUSTIFICATION positionText(String position) {
        if (position.equals(POSITION_CENTER)) {
            return EscCommand.JUSTIFICATION.CENTER;
        } else if (position.equals(POSITION_LEFT)) {
            return EscCommand.JUSTIFICATION.LEFT;
        } else {
            return EscCommand.JUSTIFICATION.RIGHT;
        }
    }

    /**
     * 打印
     */
    public void printReceiptClicked() {
        try {
            //0
            int type = mGpService.getPrinterCommandType(mPrinterIndex);
            if (type == GpCom.ESC_COMMAND) {
                //1
                int status = mGpService.queryPrinterStatus(mPrinterIndex, 500);
                if (status == GpCom.STATE_NO_ERR) {
                    sendReceipt();
                } else {
                    Log.i(DEBUG_TAG, "打印机错误");
                }
            }
        } catch (RemoteException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CONNECT_DEVICE) {
            handler.sendEmptyMessageDelayed(1, 500);
        }
    }

}
